﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using Android.App;
using Android.Util;
using MWC.BL;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Content.Res;
using Android.Accounts;

using BugSense;

namespace MWC.NetcampCheckin
{
    [Activity(Label = "NetcampHome", Icon = "@drawable/icon", WindowSoftInputMode=SoftInput.StateHidden)]
    class NetcampHome : Activity
    {
        bool tryForTheSecondTime = true;
        NetcampWebProxy.WebProxy proxy = new NetcampWebProxy.WebProxy();
        
        private String[] getUserEmails()
        {
            //Biblioteka ktora umozliwia accountmanagera intencje od wczesniejszego api
            /*AccountChooser.newChooseAccountIntent(null, null, new String[] { "com.google" }, false, null, 
                null, null, null);*/

            AccountManager accountManager = AccountManager.Get(this);
            Account[] accounts = accountManager.GetAccounts();
            int count = 0;

            foreach (var account in accounts)
            {
                if (Patterns.EmailAddress.Matcher(account.Name).Matches())
                {
                    ++count;
                }
            }

            List<String> emailsList = new List<String>();

            foreach (var account in accounts)
            {
                if (Patterns.EmailAddress.Matcher(account.Name).Matches())
                {
                    emailsList.Add(account.Name);
                }
            }
            return emailsList.Distinct().ToArray();
        }

        private bool IsValidEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return true;
            }
            catch
            {
                return false;
            }
        }

        protected override void OnCreate(Bundle bundle)
        {
            try
            {
                base.OnCreate(bundle);

                proxy.Proxy = null;

                BugSenseHandler.Instance.ClearCrashExtraData();
                BugSense.Core.Model.LimitedCrashExtraDataList extras = BugSenseHandler.Instance.CrashExtraData;

                extras.Add(new BugSense.Core.Model.CrashExtraData
                {
                    Key = "Screen",
                    Value = "NetcampHome"
                });

                SetContentView(Resource.Layout.NetcampHome);

                tryForTheSecondTime = true;

                //nawiasy, caly opis + boldTextOfSubTitle
                TextView[] tabOfBoldItems = new TextView[3];
                tabOfBoldItems[0] = FindViewById<TextView>(Resource.Id.firstParenthasesOfTitle);
                tabOfBoldItems[1] = FindViewById<TextView>(Resource.Id.secondParanthasesOfTitle);
                tabOfBoldItems[2] = FindViewById<TextView>(Resource.Id.boldTextOfSubtitle);

                setFont("fonts/texgyreheros-regular-webfont.ttf", tabOfBoldItems, TypefaceStyle.Bold);

                TextView[] tabOfSubTitle = new TextView[2];


                //pozostale, procz boldTextOfSubtitle, to ustawione w nawiasach
                int iterator = 0;

                TextView[] tabOfNormalItems = new TextView[6];
                tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.normalTextOfSubtitle);
                tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.firstInfo);
                tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.secondInfo);
                tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.Or);
                tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.EnterAdress2);
                tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.confirmButton);

                setFont("fonts/texgyreheros-regular-webfont.ttf", tabOfNormalItems, TypefaceStyle.Normal);

                EditText editEmail = FindViewById<EditText>(Resource.Id.EnterAdress2);

                //Sprawdz czy uzytkownik nie podawal maila
                var prefs = GetSharedPreferences("NetcampApp", 0);
                String mail = prefs.GetString("Email", null);
                if (mail != null)
                {
                    editEmail.Text = mail;
                    editEmail.SetTextColor(Color.Black);
                }

                editEmail.TextChanged += delegate
                {
                    editEmail.SetTextColor(Color.Black);
                };

                Button confirmButton = FindViewById<Button>(Resource.Id.confirmButton);
                confirmButton.Click += delegate
                {
                    if (IsValidEmail(editEmail.Text))
                    {
                        String[] email = { editEmail.Text };

                        // Sprawdz dwa razy czy jest odpowiedz z serwera
                        var dialog = ProgressDialog.Show(this, "Prosze czekac", "Weryfikacja danych", true);


                        new Thread(() =>
                        {
                        TwoTimes:
                            try
                            {
                                NetcampWebProxy.CheckIfUserIsRegistredResult result = proxy.CheckIfUserIsRegistred(email, DaysManager.GetLastDay().link);

                                if (result.confirmed)
                                {
                                    var prefsEditor = prefs.Edit();
                                    prefsEditor.PutInt("CurrentStep", 1);
                                    prefsEditor.PutString("Email", result.mail);
                                    prefsEditor.PutString("Name", result.username);

                                    Guid hash = Guid.NewGuid();
                                    var hashString = hash.ToString().Substring(0, 6);
                                    prefsEditor.PutString("Hash", hashString);
                                    prefsEditor.Commit();

                                    proxy.SendHashEmailToUser(result.mail, hashString);

                                    RunOnUiThread(() =>
                                        {
                                            Toast.MakeText(this, "Kod autoryzacyjny został wysłany na podany adres", ToastLength.Long).Show();
                                            Intent netcampLogin = new Intent(this, typeof(NetcampLogin));
                                            netcampLogin.PutExtra("LastActivity", true);
                                            StartActivity(netcampLogin);
                                            Finish();
                                        });
                                }
                                else
                                {
                                    RunOnUiThread(() =>
                                    {
                                        Intent showRegister = new Intent(this, typeof(NetcampRegister));
                                        StartActivity(showRegister);
                                        Finish();
                                    });
                                }

                                RunOnUiThread(() => dialog.Hide());
                            }
                            catch (Exception e)
                            {
                                MWC.MWCApp.LogDebug(e);

                                if (tryForTheSecondTime)
                                {
                                    tryForTheSecondTime = false;
                                    goto TwoTimes;
                                }
                                else
                                {
                                    RunOnUiThread(() =>
                                    {
                                        dialog.Hide();
                                        MWC.NetcampAlerts.NoInternet(this, false);
                                    });

                                }
                            }
                            tryForTheSecondTime = true;
                        }).Start();
                    }
                    else
                    {
                        Toast.MakeText(this, "Adres email jest niepoprawny", ToastLength.Long).Show();
                    }

                    tryForTheSecondTime = true;
                };

                Button getDefaultEmail = FindViewById<Button>(Resource.Id.getDefaultEmail);
                getDefaultEmail.Click += delegate
                {
                    String[] emails = getUserEmails();

                    if (emails.Length > 0)
                    {
                        //checkuj emaila
                        Intent showEmails = new Intent(this, typeof(NetcampChooseEmail));
                        showEmails.PutExtra("emails", emails);
                        StartActivity(showEmails);
                        Finish();
                        //editEmail.Text = email;
                        //editEmail.SetTextColor(Color.Black);
                    }
                    else
                    {
                        //Intent showEmails = new Intent(this, typeof(NetcampChooseEmail));
                        //showEmails.PutExtra("emails", emails);
                        //StartActivity(showEmails);
                        Toast.MakeText(this, "Nie udało się pobrać adresu email", ToastLength.Long).Show();
                    }
                };
            }
            catch (Exception e)
            {
                MWCApp.LogDebug(e);
                NetcampAlerts.UnknownError(this);
            }

       }
        // 1 - sciezka do czcionki, 2 - tablica, 3 - Typ:Bold,Italic,Normal,BoldItalic
        private void setFont(string path, TextView[] tTV, TypefaceStyle Type)
        {
            AssetManager mgr;
            mgr = Assets;
            Typeface font = Typeface.CreateFromAsset(mgr, path);
            for(int i=0;i<tTV.Length;i++)
            {
                tTV[i].SetTypeface(font, Type);
            }

        }

    }
}